<template>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    class="add-product"
    :visible.sync="visible"
    :width="handleScreenWidthToVw(590)+'px'"
    :before-close="handleClose"
  >
    <el-form ref="form" :model="formData" label-width="120px" label-suffix="：" :rules="rules">
      <el-form-item prop="name" label="产品名称">
        <el-input class="input" v-model="formData.name" maxlength="10" clearable />
      </el-form-item>
      <el-form-item prop="metadataId">
        <span slot="label">
          物模型
          <el-popover placement="top-start" trigger="hover" content="用于定义产品的属性和服务字段">
            <span slot="reference">
              <img src="@/assets/img/question.jpg" width="12px" />
              ：
            </span>
          </el-popover>
        </span>
        <selectMetadata v-if="isPublish" class="input" :metadata-id.sync="formData.metadataId" />
        <span v-else>{{ formData.metaDataVo.name }}</span>
      </el-form-item>
      <el-form-item prop="netTypeEnum" label="入网方式">
        <el-select
          v-if="isPublish"
          class="input"
          v-model="formData.netTypeEnum"
          placeholder="请选择"
        >
          <el-option
            v-for="item in netTypeList"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
        <span v-else>{{ formData.netTypeName }}</span>
      </el-form-item>
      <el-form-item v-if="formData.id" prop="deployDevice" label="接入设备数">
        {{ formData.deviceCount || 0 }}
      </el-form-item>
      <el-form-item
        prop="publishStateEnum"
        label="发布状态"
        :style="{'margin-bottom':formData.publishStateEnum === PublishState.PUBLICSHED&&!formData.id ?'0':'' }"
      >
        <div class="align-center">
          <el-switch
            :disabled="formData.deviceCount>0"
            v-model="formData.publishStateEnum"
            :active-value="PublishState.PUBLICSHED"
            :inactive-value="PublishState.UNPUBLICSHED"
          />
          <span class="mg-left-6">
            {{ formData.publishStateEnum === PublishState.PUBLICSHED ? '发布' : '未发布' }}
          </span>
        </div>
        <span
          v-if="!formData.id"
          v-show="formData.publishStateEnum===PublishState.PUBLICSHED"
          class="fz-12 lh-20 alter-text"
        >
          发布后将无法修改产品的物模型和入网方式
        </span>
        <span v-else v-show="publishErr" class="alter-text">
          <div style="color: #D12D1F;" class="lh-18">
            未发布状态切换失败：检测到当前产品已接入设备，请禁用该产品下所有设备
            <el-button
              type="text"
              style="padding: 0;color: #0084EE;"
              @click="handleNavToDeployDevice"
            >
              前往禁用
            </el-button>
          </div>
        </span>
      </el-form-item>

      <el-form-item prop="icon" label="产品图标" v-if="formData.id">
        <div class="flex-row align-center">
          <img v-if="productIcon" class="product-icon mg-right-34" :src="productIcon" alt="" />
          <select-icon @getImage="handleGetImage" />
        </div>
      </el-form-item>

      <el-form-item prop="remark" label="备注说明">
        <el-input class="input" v-model="formData.remark" type="textarea" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="justify-center">
      <el-button v-loading="loading" type="primary" @click="handleSubmit">提交</el-button>
      <el-button @click="handleClose">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { apiAddProduct, apiUpdateProduct } from '@/views/device/create-product/api'
import selectMetadata from '@/views/device/thing-model/components/selectMetadata'
import { constUtils } from '../../mixin'
import { handleScreenWidthToVw } from '@/utils/tools'
import SelectIcon from '@/components/select-icon/index.vue'

export default {
  name: 'AddProduct',
  components: { selectMetadata, SelectIcon },
  mixins: [constUtils],
  props: {
    title: { type: String, default: '新建产品' },
    visible: { type: Boolean, require: true, default: true },
    value: {
      type: Object,
      require: false,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      formData: { metaDataVo: { name: '' }, netTypeName: '' },
      loading: false,
      publishErr: false,
      model: [],
      netTypeList: [],
      productIcon: '',
    }
  },
  computed: {
    isPublish() {
      return this.formData.publishStateEnum !== this.PublishState.PUBLICSHED
    },
    rules() {
      return {
        name: [{ required: true, message: '产品名称不能为空！', trigger: 'blur' }],
        metadataId: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('物模型不能为空!'))
              }
              callback()
            },
            trigger: 'change',
          },
        ],
        netTypeEnum: [{ required: true, message: '入网方式不能为空', trigger: 'change' }],
        publishStateEnum: [{ required: true, message: '发布状态不能为空', trigger: 'change' }],
      }
    },
    handleScreenWidthToVw: () => handleScreenWidthToVw,
  },
  created() {
    this.initData()
  },
  methods: {
    initData() {
      this.formData = {
        name: '', // 产品名称
        metadataId: '', // 物模型Id
        netTypeEnum: this.NetAccessType.DIRECT, // 入网方式
        publishStateEnum: this.PublishState.UNPUBLICSHED, // 产品发布状态
        remark: '', // 备注说明
        ...this.value,
      }
      if (this.formData.icon) {
        this.productIcon = this.formData.icon
      }
      this.netTypeList = [
        { id: this.NetAccessType.DIRECT, label: this.NetAccessTypeMap[this.NetAccessType.DIRECT] },
        {
          id: this.NetAccessType.FIVE_G,
          label: this.NetAccessTypeMap[this.NetAccessType.FIVE_G],
        },
        {
          id: this.NetAccessType.GATEWAY,
          label: this.NetAccessTypeMap[this.NetAccessType.GATEWAY],
        },
      ]
    },
    handleNavToDeployDevice() {
      this.$router.push({ path: '/device/deploy-device' })
    },
    handleSubmit() {
      this.$refs.form.validate(validate => {
        if (validate) {
          if (this.formData.id) {
            this.handleSetProductIcon()
            this.updateProduct()
          } else {
            this.addProduct()
          }
        }
      })
    },
    handleClose() {
      this.loading = false
      this.initData()
      this.$emit('update:visible', false)
    },
    async addProduct() {
      this.loading = true
      try {
        await apiAddProduct(this.formData)
        this.$message.success('添加成功')
        this.$refs.form.resetFields()
        this.$emit('change')
        this.handleClose()
      } catch (e) {
        this.$message.error(e)
      }
      this.loading = false
    },
    async updateProduct() {
      try {
        await apiUpdateProduct(this.formData)
        this.$message.success('更新成功')
        this.$emit('change')
        this.handleClose()
      } catch (e) {
        this.$message.error(e)
        this.publishErr = true
      }
    },
    handleGetImage(imageStr) {
      this.productIcon = imageStr
    },
    handleSetProductIcon() {
      // await apiSetProductIcon(this.formData.id, this.productIcon)
      this.formData.icon = this.productIcon
    },
  },
}
</script>

<style scoped lang="scss">
.add-product {
  .input {
    width: vw(350px);
  }

  .help {
    position: relative;
    top: 2px;
    cursor: help;
  }

  .alter-text {
    font-size: 14px;
    line-height: 14px;
    color: #d12d1f;
  }

  .product-icon {
    width: vw(20px);
    height: auto;
    // margin-right: vw(50px);
  }
}
</style>
